package com.tianji.promotion.strategy.discount;

import com.tianji.promotion.annotation.DiscountTypeFlag;
import com.tianji.promotion.enums.DiscountType;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.EnumMap;
import java.util.Map;

public class DiscountStrategy implements ApplicationContextAware {

    private static EnumMap<DiscountType, Discount> strategies ;

    /*static {
        strategies = new EnumMap<>(DiscountType.class);
        strategies.put(DiscountType.NO_THRESHOLD, new NoThresholdDiscount());
        strategies.put(DiscountType.PER_PRICE_DISCOUNT, new PerPriceDiscount());
        strategies.put(DiscountType.RATE_DISCOUNT, new RateDiscount());
        strategies.put(DiscountType.PRICE_DISCOUNT, new PriceDiscount());
    }*/

    public static Discount getDiscount(DiscountType type) {
        return strategies.get(type);
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        strategies = new EnumMap<>(DiscountType.class);
        Map<String, Discount> beansOfType = applicationContext.getBeansOfType(Discount.class);
        beansOfType.values().forEach(bean -> {
            DiscountType key = bean.getClass().getAnnotation(DiscountTypeFlag.class).value();
            strategies.put(key,bean);
        });
    }
}
